package com.example.demo.utils;

import com.example.demo.exception.FieldException;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by lyc on 2019/5/31.
 * 直接校验工具类
 */
public class ValidatorUtils {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }


    public static void validateEntity(Object object, Class<?>... groups)
            throws FieldException {
        Set<ConstraintViolation<Object>> constraintViolations = null;
        if(groups == null){
            constraintViolations = validator.validate(object);
        }else {
            constraintViolations = validator.validate(object, groups);
        }
        if (!constraintViolations.isEmpty()) {
            Iterator<ConstraintViolation<Object>> constraintViolationIterator = constraintViolations.iterator();
            StringBuilder sb = new StringBuilder();
            while (constraintViolationIterator.hasNext()){
                ConstraintViolation constraintViolation = constraintViolationIterator.next();
                if(sb.length()>0){
                    sb.append("，");
                }
                sb.append(constraintViolation.getMessage());
            }
            throw new FieldException(sb.toString());
        }
    }


    public static void isBlank(String str, String message) {
        if (StringUtils.isEmpty(str)) {
            throw new FieldException(message);
        }
    }

    public static void isNull(Object object, String message) {
        if (object == null) {
            throw new FieldException(message);
        }
    }
}
